const { DataTypes, Model } = require('sequelize');
const { sequelize } = require('../config/database');

class Order extends Model {
  // 更新订单状态
  async updateStatus(newStatus, updatedBy, reason, notes) {
    const statusHistory = this.statusHistory || [];
    statusHistory.push({
      status: newStatus,
      timestamp: new Date(),
      updatedBy: updatedBy,
      reason: reason,
      notes: notes
    });
    
    this.status = newStatus;
    this.statusHistory = statusHistory;
    return this.save();
  }

  // 添加沟通记录
  async addCommunication(sender, recipient, message, messageType = 'text', attachments = []) {
    const communications = this.communications || [];
    communications.push({
      sender: sender,
      recipient: recipient,
      message: message,
      messageType: messageType,
      attachments: attachments,
      timestamp: new Date(),
      read: false
    });
    
    this.communications = communications;
    return this.save();
  }

  // 开始服务
  async startService() {
    const serviceReport = this.serviceReport || {};
    serviceReport.startedAt = new Date();
    
    this.status = 'in_progress';
    this.serviceReport = serviceReport;
    return this.save();
  }

  // 完成服务
  async completeService(caregiverNotes, activities = []) {
    const serviceReport = this.serviceReport || {};
    serviceReport.completedAt = new Date();
    serviceReport.caregiverNotes = caregiverNotes;
    serviceReport.activities = [...(serviceReport.activities || []), ...activities];
    
    // 计算实际服务时长
    if (serviceReport.startedAt) {
      const duration = (serviceReport.completedAt - new Date(serviceReport.startedAt)) / (1000 * 60);
      serviceReport.actualDuration = Math.round(duration);
    }
    
    this.status = 'completed';
    this.serviceReport = serviceReport;
    return this.save();
  }

  // 取消订单
  async cancelOrder(cancelledBy, reason, description, refundAmount = 0) {
    this.status = 'cancelled';
    this.cancellation = {
      cancelledBy: cancelledBy,
      cancelledAt: new Date(),
      reason: reason,
      description: description,
      refundAmount: refundAmount
    };
    
    return this.save();
  }

  // 计算退款金额
  calculateRefund() {
    const now = new Date();
    const schedule = this.schedule || {};
    const serviceStart = new Date(`${schedule.startDate} ${schedule.startTime}`);
    const hoursUntilService = (serviceStart - now) / (1000 * 60 * 60);
    
    const pricing = this.pricing || {};
    const totalAmount = pricing.totalAmount || 0;
    
    if (hoursUntilService > 24) {
      return totalAmount; // 提前24小时以上，全额退款
    } else if (hoursUntilService > 2) {
      return totalAmount * 0.5; // 提前2-24小时，50%退款
    } else {
      return 0; // 2小时内不退款
    }
  }

  // 虚拟字段: 是否活跃
  get isActive() {
    return ['pending', 'accepted', 'confirmed', 'in_progress'].includes(this.status);
  }

  // 虚拟字段: 能否取消
  get canBeCancelled() {
    const now = new Date();
    const schedule = this.schedule || {};
    const serviceStart = new Date(`${schedule.startDate} ${schedule.startTime}`);
    const hoursUntilService = (serviceStart - now) / (1000 * 60 * 60);
    
    return this.isActive && hoursUntilService > 2;
  }
}

Order.init({
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  // 订单编号
  orderNumber: {
    type: DataTypes.STRING(50),
    unique: true,
    allowNull: false
  },
  
  // 关联信息
  customerId: {
    type: DataTypes.INTEGER,
    allowNull: false,
    references: {
      model: 'users',
      key: 'id'
    }
  },
  caregiverId: {
    type: DataTypes.INTEGER,
    references: {
      model: 'caregivers',
      key: 'id'
    }
  },
  petIds: {
    type: DataTypes.JSON,
    defaultValue: []
  },
  
  // 服务详情 (JSON)
  service: {
    type: DataTypes.JSON,
    allowNull: false,
    defaultValue: {}
  },
  
  // 时间安排 (JSON)
  schedule: {
    type: DataTypes.JSON,
    allowNull: false,
    defaultValue: {}
  },
  
  // 地址信息 (JSON)
  location: {
    type: DataTypes.JSON,
    allowNull: false,
    defaultValue: {}
  },
  
  // 费用信息 (JSON)
  pricing: {
    type: DataTypes.JSON,
    allowNull: false,
    defaultValue: {
      baseAmount: 0,
      additionalCharges: [],
      discount: 0,
      totalAmount: 0,
      currency: 'CNY'
    }
  },
  
  // 订单状态
  status: {
    type: DataTypes.ENUM('pending', 'accepted', 'confirmed', 'in_progress', 'completed', 'cancelled', 'disputed'),
    defaultValue: 'pending'
  },
  
  // 状态历史 (JSON)
  statusHistory: {
    type: DataTypes.JSON,
    defaultValue: []
  },
  
  // 支付信息 (JSON)
  payment: {
    type: DataTypes.JSON,
    defaultValue: {
      method: null,
      status: 'pending',
      transactionId: null
    }
  },
  
  // 紧急情况 (JSON)
  emergency: {
    type: DataTypes.JSON,
    defaultValue: {
      isEmergency: false,
      urgencyLevel: 'low'
    }
  },
  
  // 沟通记录 (JSON)
  communications: {
    type: DataTypes.JSON,
    defaultValue: []
  },
  
  // 服务报告 (JSON)
  serviceReport: {
    type: DataTypes.JSON,
    defaultValue: {}
  },
  
  // 评价系统 (JSON)
  reviews: {
    type: DataTypes.JSON,
    defaultValue: {}
  },
  
  // 取消信息 (JSON)
  cancellation: {
    type: DataTypes.JSON,
    defaultValue: null
  },
  
  // 元数据 (JSON)
  metadata: {
    type: DataTypes.JSON,
    defaultValue: {
      source: 'web'
    }
  }
}, {
  sequelize,
  modelName: 'Order',
  tableName: 'orders',
  timestamps: true,
  indexes: [
    { fields: ['customerId'] },
    { fields: ['caregiverId'] },
    { fields: ['orderNumber'] },
    { fields: ['status'] }
  ],
  hooks: {
    beforeCreate: async (order) => {
      if (!order.orderNumber) {
        const date = new Date();
        const dateStr = date.toISOString().slice(0, 10).replace(/-/g, '');
        const randomStr = Math.random().toString(36).substring(2, 8).toUpperCase();
        order.orderNumber = `PN${dateStr}${randomStr}`;
      }
    }
  }
});

module.exports = Order;
